<template>
  <el-card>
    <el-form
      ref="formRef"
      :model="skuFormData"
      :rules="SkuFormRules"
      label-width="130px"
    >
      <el-form-item label="SPU名称"> {{ spuStore.spu.spuName }} </el-form-item>
      <el-form-item label="SKU名称" prop="skuName">
        <el-input
          type="text"
          placeholder="SKU名称"
          v-model="skuFormData.skuName"
        />
      </el-form-item>
      <el-form-item label="价格(元)" prop="price">
        <el-input-number
          placeholder="价格(元)"
          controls-position="right"
          :min="0"
          v-model="skuFormData.price"
          class="sku__input--number"
        />
      </el-form-item>
      <el-form-item label="重量(千克)" prop="weight">
        <el-input-number
          placeholder="重量(千克)"
          v-model="skuFormData.weight"
          controls-position="right"
          :min="0"
          class="sku__input--number"
        />
      </el-form-item>
      <el-form-item label="规格描述" prop="skuDesc">
        <el-input
          type="textarea"
          v-model="skuFormData.skuDesc"
          placeholder="规格描述"
          :rows="4"
        />
      </el-form-item>
      <el-form-item label="平台属性" prop="skuAttrValueList">
        <el-row :gutter="10" class="sku__row">
          <el-col
            v-for="(attrInfo, index) in attrInfoList"
            :key="attrInfo.id"
            :xs="24"
            :sm="12"
            :lg="8"
            :xl="4"
          >
            <div class="sku__col">
              <span class="sku__col--title">{{ attrInfo.attrName }}</span>
              <el-select v-model="skuFormData.skuAttrValueList[index]">
                <el-option
                  :key="attrValue.id"
                  :label="attrValue.valueName"
                  :value="`${attrInfo.id}:${attrInfo.attrName}:${attrValue.id}:${attrValue.valueName}`"
                  v-for="attrValue in attrInfo.attrValueList"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="销售属性" prop="skuSaleAttrValueList">
        <el-row :gutter="10" class="sku__row">
          <el-col
            v-for="(spuSaleAttr, index) in spuSaleAttrList"
            :key="spuSaleAttr.id"
            :xs="24"
            :sm="12"
            :lg="8"
            :xl="4"
          >
            <div class="sku__col">
              <span class="sku__col--title">
                {{ spuSaleAttr.saleAttrName }}
              </span>
              <el-select v-model="skuFormData.skuSaleAttrValueList[index]">
                <el-option
                  v-for="spuSaleAttrValue in spuSaleAttr.spuSaleAttrValueList"
                  :key="spuSaleAttrValue.id"
                  :label="spuSaleAttrValue.saleAttrValueName"
                  :value="`${spuSaleAttr.id}:${spuSaleAttr.saleAttrName}:${spuSaleAttrValue.id}:${spuSaleAttrValue.saleAttrValueName}`"
                />
              </el-select>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item
        label="图片列表"
        prop="skuImageList"
        v-model="skuFormData.skuImageList"
      >
        <el-table
          border
          :data="spuImageList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <img class="sku__img" :src="row.imgUrl" :alt="row.imgName" />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"></el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-tag type="success" v-if="row.isDefault === '1'">默认</el-tag>
              <el-button
                v-else
                @click="setSkuDefaultImg(row)"
                type="primary"
                size="small"
              >
                恢复默认
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "addSku",
};
</script>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { useSpuStore } from "@/stores/spu";
import { useCategoryStore } from "@/stores/category";
import { getSpuImageListApi, getSpuSaleAttrListApi } from "@/api/product/spu";
import { getAttrInfoList } from "@/api/product/attr";
import { addSkuApi } from "@/api/product/sku";
import type { AttrInfoList } from "@/api/product/model/attrModel";
import type {
  SpuImageList,
  SpuSaleAttrList,
} from "@/api/product/model/spuModel";
import type {
  SkuFormData,
  SkuImageList,
  SkuImageItem,
} from "@/api/product/model/skuModel";
import { ElMessage } from "element-plus";
const spuStore = useSpuStore();
const categoryStore = useCategoryStore();
// 收集数据
const formRef = ref();
const skuFormData = reactive<SkuFormData>({
  price: undefined,
  weight: undefined,
  skuName: "",
  skuDesc: "",
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
  skuImageList: [],
  skuDefaultImg: "",
});
// 发送请求获得数据
const attrInfoList = ref<AttrInfoList>([]);
onMounted(async () => {
  attrInfoList.value = await getAttrInfoList({
    category1Id: categoryStore.category1Id as number,
    category2Id: categoryStore.category2Id as number,
    category3Id: categoryStore.category3Id as number,
  });
});
const spuImageList = ref<SpuImageList>([]);
const spuSaleAttrList = ref<SpuSaleAttrList>([]);
const id = spuStore.spu.id as number;
onMounted(async () => {
  spuImageList.value = await getSpuImageListApi(id);
});
onMounted(async () => {
  spuSaleAttrList.value = await getSpuSaleAttrListApi(id);
});
// 保存按钮
const submit = async () => {
  await formRef.value.validate();
  // 发生请求
  await addSkuApi({
    ...skuFormData,
    category3Id: categoryStore.category3Id as number,
    spuId: id,
    skuAttrValueList: skuFormData.skuAttrValueList
      .filter(Boolean) // 过滤掉undefined
      .map((skuAttrValue) => {
        const [attrId, attrName, valueId, valueName] = (
          skuAttrValue as string
        ).split(":"); // 根据:切割 由于split切割完是字符串组成的数组
        return {
          attrId: +attrId, // 所以id要转为数字
          attrName,
          valueId: +valueId,
          valueName,
        };
      }),
    skuSaleAttrValueList: skuFormData.skuSaleAttrValueList
      .filter(Boolean)
      .map((skuSaleAttrValue) => {
        const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] = (
          skuSaleAttrValue as string
        ).split(":");
        return {
          saleAttrId: +saleAttrId,
          saleAttrName,
          saleAttrValueId: +saleAttrValueId,
          saleAttrValueName,
        };
      }),
  });
  // 提示用户
  ElMessage.success("SKU添加成功");
  // 返回页面
  cancel();
};
// 收集图片列表
const handleSelectionChange = (val: SkuImageList) => {
  skuFormData.skuImageList = val;
};
// 设置Sku默认图片
const setSkuDefaultImg = (row: SkuImageItem) => {
  spuImageList.value.forEach((Image) => (Image.isDefault = "0"));
  row.isDefault = "1";
  skuFormData.skuDefaultImg = row.imgUrl;
  //设置完默认图片之后要清除校验
  if (skuFormData.skuImageList.some((img) => img === row)) {
    formRef.value.clearValidate(["skuImageList"]);
  }
};
// 自定义表单校验规则
// value为选中的图片
const skuImageListValidator = (
  rule: any,
  value: SkuImageList,
  callback: any
) => {
  if (!value.length) {
    callback(new Error("请选择Sku图片"));
    return;
  }
  if (!value.some((img) => img.isDefault === "1")) {
    callback(new Error("请选择默认图片"));
    return;
  }
  callback();
};
// 表单校验
const SkuFormRules = reactive({
  skuName: [{ required: true, message: "请输入Sku名称", trigger: "blur" }],
  price: [{ required: true, message: "请输入Sku价格", trigger: "blur" }],
  weight: [{ required: true, message: "请输入Sku重量", trigger: "blur" }],
  skuDesc: [{ required: true, message: "请输入Sku规格描述", trigger: "blur" }],
  skuAttrValueList: [
    { required: true, message: "请输入Sku平台属性", trigger: "change" },
  ],
  skuSaleAttrValueList: [
    { required: true, message: "请输入Sku销售属性", trigger: "change" },
  ],
  skuImageList: [{ required: true, validator: skuImageListValidator }],
});
// 取消按钮
const emit = defineEmits(["setIsShow"]);
const cancel = () => {
  emit("setIsShow", 1);
};
</script>

<style lang="scss" scoped>
.sku__col {
  display: flex;
  margin-bottom: 10px;
}
.sku__col--title {
  flex-grow: 1;
  text-align: right;
  margin-right: 10px;
}
.sku__row {
  width: 100%;
}
.sku__input--number {
  width: 100%;
  :deep(.el-input__inner) {
    text-align: left;
  }
}
.sku__img {
  width: 100px;
  height: 100px;
}
</style>
